﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Reflection;

namespace PPP.Utils {
    /// <summary>
    /// Helper Class to encrypt the application settings.
    /// 
    /// <list type="bullet">
    /// <item>
    /// <term>Author</term>
    /// <description>Sebastian Will</description>
    /// </item>
    /// </list>
    /// 
    /// </summary>  
    public class WebConfigEncryption {

        #region Fields

        private readonly DpapiProtectedConfigurationProvider _provider;
        private readonly MethodInfo _encryptTextMethod;
        private readonly MethodInfo _decryptTextMethod;

        #endregion


        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        public WebConfigEncryption() {
            _provider = new DpapiProtectedConfigurationProvider();
            _encryptTextMethod = _provider.GetType().GetMethod("EncryptText", BindingFlags.Instance | BindingFlags.NonPublic);
            _decryptTextMethod = _provider.GetType().GetMethod("DecryptText", BindingFlags.Instance | BindingFlags.NonPublic);
        }

        #endregion

        #region Methods

        /// <summary>
        /// Encrypt a value. 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string Encrypt(string value) {
            var encryptedValue = value != null ? (string)_encryptTextMethod.Invoke(_provider, new object[] { value }) : null;

            return encryptedValue;
        }

        /// <summary>
        /// Decrypt a value.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public string Decrypt(string value) {
            var decryptedValue = value != null ? (string)_decryptTextMethod.Invoke(_provider, new object[] { value }) : null;

            return decryptedValue;
        }

        #endregion
    }
}
